package db_sports

import (
	"context"
	"encoding/json"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_sports"

	"github.com/olivere/elastic/v7"
	"gorm.io/gorm"
)

const (
	MatchStaring  = 1
	MatchPending  = 2
	MatchFinished = 3

	FootBallSportId   = 1
	BasketBallSportId = 2
)

func GetEsIdByInfo(id int, sportID int) (*api_models.EsMatchTempSchedule, error) {
	var query elastic.Query
	var sportQuery elastic.Query
	query = elastic.NewTermQuery("match_id", id)
	search := global2.GetEs().Search().Index(models_sports.MatchTempSchedule{}.TableName())
	if sportID != 0 {
		sportQuery = elastic.NewTermQuery("sport_id", sportID)
		query = elastic.NewBoolQuery().Must(query).Must(sportQuery)
	} else {
		query = elastic.NewBoolQuery().Must(query)
	}
	searchResult, err := search.Size(1).Timeout(_const.ES_SEARCH_TIME_OUT).Query(query).Do(context.Background())

	if err != nil {
		global2.Log.Errorf("searchAnchor err:%v", err)
		return nil, err
	}
	resp := &api_models.EsMatchTempSchedule{}
	if searchResult.Hits.TotalHits.Value > 0 {
		hit := searchResult.Hits.Hits[0]
		err = json.Unmarshal(hit.Source, resp)
		if err != nil {
			global2.Log.Errorf("GetEsIdByInfo Unmarshal err:%v", err)
			return nil, err
		}
	}
	return resp, nil
}

func GetMysqlIdByInfo(id int, sportID int) (*api_models.EsMatchTempSchedule, error) {
	match := &api_models.EsMatchTempSchedule{}
	query := global2.Sport().Model(&models_sports.MatchesSchedule{}).Where("match_id=?", id)
	if sportID != 0 {
		query.Where("sport_id=?", sportID)
	}
	err := query.First(&match).Error
	if err != nil {
		return nil, err
	}
	return match, nil
}

//55直播赛事列表
/**sport_id 1.足球 2.篮球 3.热门 4.全部
matchStateId 1.进行中 2.赛程  3.赛果*/
func Get55MatchList(db *gorm.DB, sportId int, comp string, matchStateId int, matchDate int64) []*models_sports.MatchTempSchedule {
	limitNum := 15
	if sportId == 4 && matchStateId == 1 {
		limitNum = 8
	}
	var data []*models_sports.MatchTempSchedule
	var rs1 []*models_sports.MatchTempSchedule //进行中
	var rs2 []*models_sports.MatchTempSchedule //未开赛
	var rs3 []*models_sports.MatchTempSchedule //赛果
	//params["match_time"] = map[string]interface{}{">=": startTime, "<=": endTime}
	rs1Where := make(map[string]interface{})
	rs2Where := make(map[string]interface{})
	rs3Where := make(map[string]interface{})
	if sportId == 4 { //全部
		if matchStateId == MatchStaring {
			rs1Where["match_status"] = 1
			rs2Where["match_status"] = 2
			rs3Where["match_status"] = 3
		} else if matchStateId == MatchPending {
			rs2Where["match_status"] = 2
		} else if matchStateId == MatchFinished {
			rs3Where["match_status"] = 3
		}
	} else if sportId == 3 { //热门
		if matchStateId == MatchStaring {
			rs1Where["focus"] = 2
			rs1Where["match_status"] = 1
			rs2Where["match_status"] = 2
			rs2Where["focus"] = rs1Where["focus"]
			rs3Where["match_status"] = 3
			rs3Where["focus"] = rs1Where["focus"]
		} else if matchStateId == MatchPending {
			rs2Where["match_status"] = 2
			rs2Where["focus"] = 2
		} else if matchStateId == MatchFinished {
			rs3Where["match_status"] = 3
			rs3Where["focus"] = 2
		}
	} else if sportId == 2 { //篮球
		if matchStateId == MatchStaring {
			rs1Where["sport_id"] = BasketBallSportId
			rs1Where["match_status"] = 1
			rs2Where["match_status"] = 2
			rs2Where["sport_id"] = rs1Where["sport_id"]
			rs3Where["match_status"] = 3
			rs3Where["sport_id"] = rs1Where["sport_id"]
		} else if matchStateId == MatchPending {
			rs2Where["match_status"] = 2
			rs2Where["sport_id"] = BasketBallSportId
		} else if matchStateId == MatchFinished {
			rs3Where["match_status"] = 3
			rs3Where["sport_id"] = BasketBallSportId
		}
	} else if sportId == 1 { //足球
		if matchStateId == MatchStaring {
			rs1Where["sport_id"] = FootBallSportId
			rs1Where["match_status"] = 1
			rs2Where["match_status"] = 2
			rs2Where["sport_id"] = FootBallSportId
			rs3Where["match_status"] = 3
			rs3Where["sport_id"] = FootBallSportId
		} else if matchStateId == MatchPending {
			rs2Where["match_status"] = 2
			rs2Where["sport_id"] = FootBallSportId
		} else if matchStateId == MatchFinished {
			rs3Where["match_status"] = 3
			rs3Where["sport_id"] = FootBallSportId
		}
	} else if len(comp) > 1 {
		if matchStateId == MatchStaring {
			rs1Where["comp_short_zh"] = comp
			rs1Where["match_status"] = 1
			rs2Where["match_status"] = 2
			rs2Where["comp_short_zh"] = comp
			rs3Where["match_status"] = 3
			rs3Where["comp_short_zh"] = comp
		} else if matchStateId == MatchPending {
			rs2Where["match_status"] = 2
			rs2Where["comp_short_zh"] = comp
		} else if matchStateId == MatchFinished {
			rs3Where["match_status"] = 3
			rs3Where["comp_short_zh"] = comp
		}
	}
	//global.Log.Debugf("rs1Where:%v,rs2Where:%v,rs3Where:%v", rs1Where, rs2Where, rs3Where)
	if len(rs1Where) < 1 && len(rs2Where) < 1 && len(rs3Where) < 1 {
		return data
	}
	matchEndDate := matchDate + 86400

	if len(rs1Where) > 0 {
		if matchDate > 0 {
			rs1Where["match_time"] = map[string]interface{}{">=": matchDate, "<": matchEndDate}
		}
		table := db.Model(&models_sports.MatchTempSchedule{})
		mysql.Condition(table, rs1Where, "", "match_time desc", 1, limitNum)
		table.Find(&rs1)
		data = append(data, rs1...)
	}
	if len(rs2Where) > 0 {
		if matchDate > 0 && matchStateId != MatchStaring {
			rs2Where["match_time"] = map[string]interface{}{">=": matchDate, "<": matchEndDate}
		}
		table := db.Model(&models_sports.MatchTempSchedule{})
		mysql.Condition(table, rs2Where, "", "match_time asc", 1, limitNum)
		table.Find(&rs2)
		data = append(data, rs2...)
	}
	if len(rs3Where) > 0 {
		if matchDate > 0 && matchStateId != MatchStaring {
			rs3Where["match_time"] = map[string]interface{}{">=": matchDate - 86400, "<": matchDate}
		}
		table := db.Model(&models_sports.MatchTempSchedule{})
		mysql.Condition(table, rs3Where, "", "match_time desc", 1, limitNum)
		table.Find(&rs3)
		data = append(data, rs3...)
	}
	return data
}

func HotLeague(db *gorm.DB) ([]*models_sports.LeagueName, error) {
	var resp []*models_sports.LeagueName
	stime, etime := timehelper.INaDay2Unix("")
	err := db.Model(models_sports.MatchTempSchedule{}).Select("comp_short_zh").Where("match_time >= ? and match_time <= ?", stime, etime).Group("comp_short_zh").Find(&resp).Error
	if err != nil {
		return nil, err
	}
	return resp, nil
}
